﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace ServiceHost
{
    public class HotSpotHelper
    {
        //http://sentinel.ga.gov.au/acres/sentinel/rssfeed.shtml
        public static HotSpot[] GetHotSpots(Coordinate coordinate)
        {
            //TODO: Get RSS Feed
            var hotSpots = GetAllHotSpots();

            //TODO: Filter HotSpots, improve performance
            var filteredHotSpots = from e in hotSpots where e.Coordinate.Distance(coordinate) < Const.MaxHotSpotDistance select e;

            var res = filteredHotSpots.ToArray();
            return res;
        }

        private const string FeedUrl = "http://sentinel.ga.gov.au/RSS/sentinelrss.xml";

        public static List<HotSpot> GetAllHotSpots()
        {
            XDocument feedXml = null;
     
            try
            {
                feedXml = XDocument.Load(FeedUrl);
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine("Failed to loaded feed");
            }

            Console.WriteLine("GetFeedItems");

            if (feedXml == null)
                return null;

            System.Diagnostics.Debug.WriteLine("Getting latest feed");

            XNamespace georss = XNamespace.Get("http://www.georss.org/georss");

            //<pubDate>Thu, 31 May 2012 04:49:10 GMT</pubDate>
            //<description>
            //<![CDATA[LOCATION: -11.608 133.068<br/>TEMPERATURE: 42.0C<br/>CONFIDENCE: 63%<br/>SATELLITE: aqua<br/>OBS TIME: 2012-05-31T04:49:10Z<br/>GRID: 1km]]>
            //</description>
            //<georss:point>-11.608 133.068</georss:point>

            //TODO: Add proper parsing and validation
            //Parse description to get attributes - RegEx?
            var hotSpots = from element in feedXml.Descendants("item")
                           select new HotSpot()
                                      {
                                          Description = element.Element("description").Value,
                                          PubDate = element.Element("pubDate").Value,
                                          Coordinate = new Coordinate(element.Element(georss + "point").Value),
                                      };

            System.Diagnostics.Debug.WriteLine("Got {0} feed items", hotSpots.Count());

            return hotSpots.ToList();
        }
    }
}